package com.ys.nms.module.business.controller.admin.redData;

import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 端口统计数据专用解析器
 */
@Component
@AllArgsConstructor
public class PortStatsDataParser {

    private static final List<String> PORT_COLUMNS = Arrays.asList(
            "INOCTETS", "OUTOCTETS", "INERRORS", "OUTERRORS",
            "INUCASTPKTS", "OUTUCASTPKTS", "INNUCASTPKTS", "OUTNUCASTPKTS",
            "INDISCARDS", "OUTDISCARDS", "INUNKNOWNPROTOS",
            "INBROADCASTPKTS", "OUTBROADCASTPKTS", "INMULTICASTPKTS", "OUTMULTICASTPKTS"
    );

    private final RrdMultiColumnReader rrdMultiReader;

    /**
     * 解析端口统计数据
     */
    public RrdMultiQueryResult parsePortStats(RrdQueryParams params) {
        RrdMultiQueryResult result = rrdMultiReader.queryMultiColumnRrdData(params);

        if (result.getSuccess()) {
            System.out.println("端口数据解析完成: {}个时间点，有效列: {}" +
                    result.getTotalPoints() + result.getValidPointsPerColumn());
        }

        return result;
    }

    /**
     * 获取流量统计（入站+出站）
     */
    public Map<String, Object> getTrafficStats(RrdMultiQueryResult result) {
        List<Double> inOctets = new ArrayList<>();
        List<Double> outOctets = new ArrayList<>();

//        for (RrdMultiDataPoint point : result.getDataPoints()) {
//            if (point.isMetricValid("INOCTETS")) {
//                inOctets.add(point.getMetric("INOCTETS"));
//            }
//            if (point.isMetricValid("OUTOCTETS")) {
//                outOctets.add(point.getMetric("OUTOCTETS"));
//            }
//        }

        double totalIn = inOctets.stream().mapToDouble(Double::doubleValue).sum();
        double totalOut = outOctets.stream().mapToDouble(Double::doubleValue).sum();

        return Map.of(
                "inOctetsCount", inOctets.size(),
                "outOctetsCount", outOctets.size(),
                "totalInTraffic", String.format("%.2f", totalIn),
                "totalOutTraffic", String.format("%.2f", totalOut),
                "totalTraffic", String.format("%.2f", totalIn + totalOut)
        );
    }

    /**
     * 获取错误率统计
     */
    public Map<String, Object> getErrorStats(RrdMultiQueryResult result) {
        // 计算错误率: 错误数/(正确包数+错误数)
        // 这里需要根据具体业务逻辑实现
        return Map.of(
                "inErrors", result.getValidPointsPerColumn().getOrDefault("INERRORS", 0),
                "outErrors", result.getValidPointsPerColumn().getOrDefault("OUTERRORS", 0)
        );
    }
}